package com.sunshine.simplehospital.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.IdRes
import androidx.annotation.LayoutRes
import androidx.core.view.ViewCompat
import androidx.fragment.app.Fragment

/**
 * Created by sunshine on 2020/4/28
 */

class DefaultFragment : Fragment(){
    private val KEY_LAYOUT_RES_ID = "KEY_LAYOUT_RES_ID"
    private val KEY_TRANSITION_NAME = "KEY_TRANSITION_NAME"
    private val KEY_TRANSITION_NAME_VIEW_ID = "KEY_TRANSITION_NAME_VIEW_ID"

    private var layoutResId = 0
    private var transitionName: String? = null
    private var transitionNameViewId = 0

    fun newInstance(@LayoutRes layoutResId: Int): DefaultFragment? {
        return newInstance(layoutResId, null)
    }

    fun newInstance(
        @LayoutRes layoutResId: Int, transitionName: String?
    ): DefaultFragment? {
        return newInstance(layoutResId, transitionName, View.NO_ID)
    }

    fun newInstance(
        @LayoutRes layoutResId: Int,
        transitionName: String?,
        @IdRes transitionNameViewId: Int
    ): DefaultFragment? {
        val fragment = DefaultFragment()
        val args = Bundle()
        args.putInt(KEY_LAYOUT_RES_ID, layoutResId)
        args.putString(KEY_TRANSITION_NAME, transitionName)
        args.putInt(KEY_TRANSITION_NAME_VIEW_ID, transitionNameViewId)
        fragment.arguments = args
        return fragment
    }

    override fun onCreate(bundle: Bundle?) {
        super.onCreate(bundle)
        val args = arguments
        if (args != null) {
            layoutResId = args.getInt(KEY_LAYOUT_RES_ID)
            transitionName = args.getString(KEY_TRANSITION_NAME)
            transitionNameViewId = args.getInt(KEY_TRANSITION_NAME_VIEW_ID)
        }
    }

    override fun onCreateView(
        layoutInflater: LayoutInflater, viewGroup: ViewGroup?, bundle: Bundle?
    ): View? {
        return layoutInflater.inflate(layoutResId, viewGroup, false /* attachToRoot */)
    }

    override fun onViewCreated(view: View, bundle: Bundle?) {
        if (transitionName != null) {
            val transitionNameView =
                if (transitionNameViewId == View.NO_ID) view else view.findViewById(
                    transitionNameViewId
                )
            ViewCompat.setTransitionName(transitionNameView, transitionName)
        }
    }
}